package com.photoeditor.demo.ui.widget;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateInterpolator;

import com.photoeditor.R;
import com.photoeditor.demo.util.ImageRectUtils;

/**
 * 编辑界面滤镜选中时的动画
 * bgHeight
 * bgWidth需要写死
 * 这里有两中动画：
 * （1）一个色块上升扩大的动画
 * （2）一个色块往中间聚集的动画
 */
public class AnimationTextView extends View {

    /**
     * 用于绘制Text
     */
    private StaticLayout mTextLayout;

    /**
     * 用于存储需要绘制的Text
     */
    private String mText;

    /**
     * 绘制Text的Paint
     */
    private TextPaint mTextPaint;

    /**
     * 用于控制是否显示Text
     */
    private boolean mShowText = true;

    /**
     * 文字的宽度
     */
    private float mTextWidth;

    /**
     * Text的开始位置
     */
    private float mTextLeft;
    private float mTextTop;

    /**
     * Text的颜色
     */
    private int mTextColor;

    /**
     * Text的大小
     */
    private int mTextSize;

    /**
     * 背景颜色
     */
    private int mBgColor;

    /**
     * View的Rect
     */
    private RectF mRect;

    /**
     * 最大值默认为100
     */
    private int mProgress = 0;

    /**
     * 是否初始化完成
     */
    private boolean mIsInit = false;

    /**
     * 动画辅助用于产生顺划的值
     */
    private ObjectAnimator mInAnimation;

    /**
     * 动画辅助用于产生顺划的值
     */
    private ObjectAnimator mOutAnimation;

    /**
     * 是否在动画中
     */
    private boolean mIsAnimation = false;


    /**
     * 下面这四个用于色块上升扩大的动画
     * mBgPaint 用于绘制色块上升扩大的动画
     * mDrawBgRect 绘制背景的Rect
     * 默认的背景的高度和宽度
     * 是动画1中出现的
     */
    private Paint mBgPaint;
    private RectF mDrawBgRect;
    private int mDefaultBgHeight;
    private int mDefaultBgWidth;


    /**
     * 下面这四个用于实现往中间聚集的动画
     * mRectPaint 是动画2的Paint
     * mBorderRect 是动画2的Border
     * mDefaultBorderWidth 是动画2默认的Border的宽度  这个的意思是两边的Border之和
     * mBorderWidth 是动画2当前Border的宽度
     */
    private Paint mRectPaint;
    private RectF mBorderRect;
    private float mDefaultBorderWidth;
    private float mBorderWidth;

    public AnimationTextView(Context context) {
        this(context, null);
    }

    public AnimationTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mIsInit) {
            /**
             * 动画一
             */
//			canvas.drawRect(mDrawBgRect, mBgPaint);

            /**
             * 动画二
             */
            canvas.drawRect(mBorderRect, mRectPaint);
            if (mShowText && mTextLayout != null) {
                int count = canvas.save();
                canvas.translate(mTextLeft, mTextTop);
                mTextLayout.draw(canvas);
                canvas.restoreToCount(count);
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed) {
            doInit();
        }
    }

    private void init(AttributeSet attrs) {
        setWillNotDraw(false);
        setLayerType(LAYER_TYPE_HARDWARE, null);
        Resources res = getResources();
        if (attrs != null) {
            TypedArray typedArray = getResources().obtainAttributes(attrs, R.styleable.AnimationTextView);
            mTextColor = typedArray.getColor(R.styleable.AnimationTextView_animationTextColor, Color.WHITE);
            mBgColor = typedArray.getColor(R.styleable.AnimationTextView_bgColor, Color.TRANSPARENT);
            mTextSize = typedArray.getDimensionPixelSize(R.styleable.AnimationTextView_animationTextSize,
                    res.getDimensionPixelSize(R.dimen.image_edit_seekbar_num_size));
            mDefaultBgHeight = typedArray.getDimensionPixelSize(R.styleable.AnimationTextView_bgHeight, 0);
            mDefaultBgWidth = typedArray.getDimensionPixelSize(R.styleable.AnimationTextView_bgWidth, 0);
            mDefaultBorderWidth = typedArray.getDimensionPixelSize(R.styleable.AnimationTextView_borderWeight,
                    res.getDimensionPixelSize(R.dimen.animation_textview_border_width));
            typedArray.recycle();
        } else {
            mTextColor = Color.WHITE;
            mBgColor = Color.TRANSPARENT;
            mTextSize = res.getDimensionPixelSize(R.dimen.image_edit_seekbar_num_size);
            mDefaultBgHeight = 0;
            mDefaultBgWidth = 0;
            mDefaultBorderWidth = res.getDimensionPixelSize(R.dimen.animation_textview_border_width);
        }
        mBorderWidth = mDefaultBorderWidth;
        mText = "";
    }

    private void doInit() {
        if (!mIsInit) {
            mIsInit = true;
            mRect = ImageRectUtils.getViewRect(this);
            mDrawBgRect = new RectF(0, mRect.height() - mDefaultBgHeight, mRect.width(), mRect.height());
            mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
            mTextPaint.setFakeBoldText(true);
            mTextPaint.setColor(mTextColor);
            mTextPaint.setTextSize(mTextSize);
            mTextPaint.setShadowLayer(3, 0, 0, Color.BLACK);
            mBgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mBgPaint.setColor(mBgColor);

            if (mProgress != 0) {
                mDrawBgRect.top = mRect.height() - ((mRect.height() - mDefaultBgHeight) / 100 * mProgress + mDefaultBgHeight);
                mBorderWidth = ((mRect.width() - mDefaultBorderWidth)) / 100 * mProgress + mDefaultBorderWidth;
            }
            mBorderRect = new RectF();
            mBorderRect.set(0, 0, mRect.width(), mRect.height());

            mRectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mRectPaint.setColor(mBgColor);
            mRectPaint.setStyle(Paint.Style.STROKE);
            mRectPaint.setStrokeWidth(mBorderWidth);

            mTextWidth = StaticLayout.getDesiredWidth(mText, mTextPaint);

            /**
             * 注意最后一个参数是默认的变成...的长度
             */
            mTextLayout = new StaticLayout(mText, 0, mText.length(), mTextPaint, (int) (mTextWidth + 1), Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
                    false, TruncateAt.END, mDefaultBgWidth - (int) mDefaultBorderWidth);
            int textHeight = mTextLayout.getHeight();
            mTextLeft = mDrawBgRect.left + (mDrawBgRect.width() - mTextWidth) / 2;
            mTextLeft = Math.max(mTextLeft, mDefaultBorderWidth / 2);
            mTextTop = mDrawBgRect.top + (mDrawBgRect.height() - textHeight) / 2;
            invalidate();
        }
    }

    /**
     * 设置文字
     *
     * @param text
     */
    public void setText(String text) {
        if (TextUtils.isEmpty(text)) {
            mText = "";
        } else {
            mText = text;
        }
        if (mIsInit) {
            mTextWidth = StaticLayout.getDesiredWidth(mText, mTextPaint);
            mTextLayout = new StaticLayout(mText, 0, mText.length(), mTextPaint, (int) (mTextWidth + 1), Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
                    false, TruncateAt.END, mDefaultBgWidth - (int) mDefaultBorderWidth);
            int textHeight = mTextLayout.getHeight();
            mTextLeft = mDrawBgRect.left + (mDrawBgRect.width() - mTextWidth) / 2;
            mTextLeft = Math.max(mTextLeft, mDefaultBorderWidth / 2);
            mTextTop = mDrawBgRect.top + (mDrawBgRect.height() - textHeight) / 2;
            invalidate();
        }
    }

    /**
     * 设置文字颜色
     *
     * @param color
     */
    public void setTextColor(int color) {
        mTextColor = color;
        if (mIsInit) {
            mTextPaint.setColor(color);
            mTextWidth = StaticLayout.getDesiredWidth(mText, mTextPaint);
            mTextLayout = new StaticLayout(mText, 0, mText.length(), mTextPaint, (int) (mTextWidth + 1), Alignment.ALIGN_NORMAL, 1.0f, 0.0f,
                    false, TruncateAt.END, mDefaultBgWidth - (int) mDefaultBorderWidth);
            invalidate();
        }
    }

    /**
     * 设置背景颜色
     *
     * @param color
     */
    public void setBgColor(int color) {
        mBgColor = color;
        if (mIsInit) {
            mBgPaint.setColor(mBgColor);
            mRectPaint.setColor(mBgColor);
            invalidate();
        }
    }

    /**
     * 启动动画
     *
     * @param duration
     */
    public void startInAnimation(int duration, boolean showText) {
        if (mOutAnimation != null) {
            mOutAnimation.cancel();
            mIsAnimation = false;
        }
        mShowText = showText;
        if (mIsInit) {
            if (mInAnimation == null) {
                mInAnimation = ObjectAnimator.ofInt(this, "progress", 0, 100);
                mInAnimation.setInterpolator(new AccelerateInterpolator(2.0f));
                mInAnimation.addListener(new AnimatorListener() {

                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mIsAnimation = false;
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        mIsAnimation = false;
                    }
                });
            }
            mInAnimation.setDuration(duration);
            mInAnimation.start();
            mIsAnimation = true;
        }
    }

    /**
     * 启动动画
     *
     * @param duration
     */
    public void startOutAnimation(int duration, boolean showText) {
        if (mInAnimation != null) {
            mInAnimation.cancel();
            mIsAnimation = false;
        }
        mShowText = showText;
        if (mIsInit) {
            if (mOutAnimation == null) {
                mOutAnimation = ObjectAnimator.ofInt(this, "progress", 100, 0);
                mOutAnimation.setInterpolator(new AccelerateInterpolator(2.0f));
                mOutAnimation.addListener(new AnimatorListener() {

                    @Override
                    public void onAnimationStart(Animator animation) {

                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        mIsAnimation = false;
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        mIsAnimation = false;
                    }
                });
            }
            mOutAnimation.setDuration(duration);
            mOutAnimation.start();
            mIsAnimation = true;
        }
    }

    public int getProgress() {
        return mProgress;
    }

    /**
     * 动画时使用
     *
     * @param progress
     */
    public void setProgress(int progress) {
        if (mIsAnimation) {
            mProgress = progress;
            if (mIsInit) {
                mDrawBgRect.top = mRect.height() - ((mRect.height() - mDefaultBgHeight) / 100 * mProgress + mDefaultBgHeight);
                mBorderWidth = ((mRect.width() - mDefaultBorderWidth)) / 100 * mProgress + mDefaultBorderWidth;
                mRectPaint.setStrokeWidth(mBorderWidth);
                int textHeight = mTextLayout.getHeight();
                mTextTop = mDrawBgRect.top + (mDrawBgRect.height() - textHeight) / 2;
                invalidate();
            }
        }
    }

    /**
     * showText是是否显示Text
     *
     * @param progress
     * @param showText
     */
    public void setProgressAndCancelAnimation(int progress, boolean showText) {
        if (mInAnimation != null) {
            mInAnimation.cancel();
            mIsAnimation = false;
        }
        mShowText = showText;
        mProgress = progress;
        if (mIsInit) {
            mDrawBgRect.top = mRect.height() - ((mRect.height() - mDefaultBgHeight) / 100 * mProgress + mDefaultBgHeight);
            mBorderWidth = ((mRect.width() - mDefaultBorderWidth)) / 100 * mProgress + mDefaultBorderWidth;
            mRectPaint.setStrokeWidth(mBorderWidth);
            int textHeight = mTextLayout.getHeight();
            mTextTop = mDrawBgRect.top + (mDrawBgRect.height() - textHeight) / 2;
            invalidate();
        }
    }
}
